﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.ServiceProcess;
using System.Configuration.Install;

namespace ServerForm
{

    public class ServiceManager
    {
       
        /// <summary>
        /// 安装服务
        /// </summary>
        /// <param name="stateSever"></param>
        /// <param name="filepath"></param>
        /// <param name="servicename"></param>
        public void InstallService(IDictionary stateSever, string filepath, string servicename)
        {
            try
            {
                System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(servicename);
                if (!ServiceIsExisted(servicename))
                {
                    AssemblyInstaller myassemblyinstaller = new AssemblyInstaller();
                    myassemblyinstaller.UseNewContext = true;
                    myassemblyinstaller.Path = filepath;
                    stateSever.Clear();
                    myassemblyinstaller.Install(stateSever);
                    myassemblyinstaller.Commit(stateSever);
                    myassemblyinstaller.Dispose();
                    service.Start();
                }
                else
                {
                    if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending)
                    {
                        service.Start();
                    }
                }


            }
            catch (Exception ee)
            {

                throw new Exception("installServiceError\n" + ee.Message);

            }
        }

        /// <summary>
        /// 卸载服务
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="servicename"></param>
        public void UnInstallService(string filepath, string servicename)
        {
            try
            {
                if (ServiceIsExisted(servicename))
                {
                    //UnInstall Service
                    AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller();
                    myAssemblyInstaller.UseNewContext = true;
                    myAssemblyInstaller.Path = filepath;
                    myAssemblyInstaller.Uninstall(null);
                    myAssemblyInstaller.Dispose();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("unInstallServiceError\n" + ex.Message);
            }
        }


        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="serviceName"></param>
        public void StartService(string serviceName)
        {
            if (ServiceIsExisted(serviceName))
            {
                System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName);
                if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending)
                {
                    service.Start();
                    for (int i = 0; i < 60; i++)
                    {
                        service.Refresh();
                        System.Threading.Thread.Sleep(1000);
                        if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running)
                        {
                            break;
                        }
                        if (i == 59)
                        {
                            throw new Exception(serviceName + "启动错误");
                        }
                    }
                }
            }
        }


        /// <summary>
        /// 停止服务
        /// </summary>
        /// <param name="serviceName"></param>
        public void StopService(string serviceName)
        {
            if (ServiceIsExisted(serviceName))
            {
                System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName);
                if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running)
                {
                    service.Stop();
                    for (int i = 0; i < 60; i++)
                    {
                        service.Refresh();
                        System.Threading.Thread.Sleep(1000);
                        if (service.Status == System.ServiceProcess.ServiceControllerStatus.Stopped)
                        {
                            break;
                        }
                        if (i == 59)
                        {
                            throw new Exception(serviceName + "停止错误");
                        }
                    }
                }
            }
        }

        /// <summary>
        ///服务运行状态
        /// </summary>
        /// <param name="serviceName">服务名</param>
        /// <returns>状态</returns>
        public EnumServiceStatus GetServiceStatus(string serviceName)
        {
            EnumServiceStatus status = EnumServiceStatus.CannotGet;

            System.ServiceProcess.ServiceController[] scs;

            scs = System.ServiceProcess.ServiceController.GetServices();

            foreach (System.ServiceProcess.ServiceController sc in scs)
            {
                if (serviceName.ToUpper() == sc.ServiceName.ToUpper())
                {
                    switch (sc.Status)
                    {
                        case System.ServiceProcess.ServiceControllerStatus.Stopped:
                            // 停止状態
                            status = EnumServiceStatus.Stopped;
                            break;
                        case System.ServiceProcess.ServiceControllerStatus.StartPending:
                            // 開始中
                            status = EnumServiceStatus.StartPending;
                            break;
                        case System.ServiceProcess.ServiceControllerStatus.Running:
                            // 运行中
                            status = EnumServiceStatus.Running;
                            break;
                        case System.ServiceProcess.ServiceControllerStatus.StopPending:
                            // 停止中
                            status = EnumServiceStatus.StopPending;
                            break;
                        case System.ServiceProcess.ServiceControllerStatus.PausePending:
                            // 一時中断中
                            status = EnumServiceStatus.PausePending;
                            break;
                        case System.ServiceProcess.ServiceControllerStatus.Paused:
                            // 一時中断
                            status = EnumServiceStatus.Paused;
                            break;
                        case System.ServiceProcess.ServiceControllerStatus.ContinuePending:
                            // 保留中
                            status = EnumServiceStatus.ContinuePending;
                            break;
                    }
                    break;
                }
            }

            return status;
        }


        public enum EnumServiceStatus
        {
            Stopped,
            StartPending,
            Running,
            StopPending,
            PausePending,
            Paused,
            ContinuePending,
            CannotGet
        }



        /// <summary>
        /// 判断服务是否存在
        /// </summary>
        /// <param name="serviceName">服务名</param>
        /// <returns>真 存在 假 不存在</returns>
        private bool ServiceIsExisted(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController s in services)
            {
                if (s.ServiceName == serviceName)
                {
                    return true;
                }
            }
            return false;
        }



    }
}
